import React, { PureComponent } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Popconfirm, message, Button, Modal, Row, Col } from 'antd';
import { BaseForm } from '@/components/FormTools';
import { saveCityPayment } from '@/services/auth';
import { StandardTable, SearchForm } from '@joy/joy-pro';
import { to } from '@/utils/smallTool';
import { connect } from 'dva';
import configData from './config-data';
import styles from './index.less';
import Push from './Push';
import { pushedNoticeSingle, pushedNoticeList } from '@/services/push';
import CryptoJS from 'crypto-js';


const pageInfo = { showSizeChanger: true, showQuickJumper: true, defaultPageSize: 20 };
const drawerWidth = 500;
const handleCommand = {
  commands: [],
  add(command) {
    this.commands.push(command);
  },
  execute(type) {
    this.commands.forEach((command) => {
      command()
    })
    this.commands = [];
  }
};
@connect(({ global, loading, citypay, allcity }) => ({
  tableData: citypay.tableData,
  cityList: allcity.cityList,
  tableLoading: loading.effects['citypay/getCityPaymentList'],
  watermarkConfig: global.watermarkConfig,
}))
class CityPay extends PureComponent {
  constructor(props) {
    super(props);
    this.$drawerForm = React.createRef();
    this.$pushDrawerForm = React.createRef();
    this.state = {
      params: {},
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
      },
      drawerStatus: {
        pay: { visible: false },
        push: { visible: false },
      },
      activeRecord: {},
      inputConfig: configData.getSearchInputConfig(props.cityList)

    };
    const { pageRequest, params } = this.state;
    this.getSelectList();
    this.refreshList();
  }
  // 条件筛选
  /**
   * @description 条件筛选 [搜索]
   * @author zhe
   * @date 2020-04-13
   * @param {*} formData
   * @param {*} reaclData
   * @param {*} isClear
   * @memberof
   */
  actionSearch = (formData, reaclData, isClear) => {
    const params = formData;
    const pageRequest = { pageNum: 1, pageSize: 10 };
    this.setState({
      params: params,
    });
    this.getQueryList(params, pageRequest);
  };
  /**
   * @description 请求列表数据
   * @author zhe
   * @date 2020-04-13
   * @param {*} params
   * @param {*} pageRequest
   * @memberof
   */
  getQueryList = (params, pageRequest) => {
    const type = 'citypay/getCityPaymentList';
    const param = Object.assign(pageRequest, params);
    const { dispatch } = this.props;
    dispatch({
      type,
      payload: param,
    });
  };
  refreshList(pageRequest = { pageNum: 1, pageSize: 10 }) {
    this.getQueryList(this.state.params, pageRequest);
  };
  /**
   * @description 请求事件类型下拉列表数据
   * @author zhe
   * @date 2020-04-14
   * @memberof
   */
  getSelectList = async () => {
    const type = 'allcity/getCityByPage';
    const { dispatch } = this.props;
    const cityList = await dispatch({
      type
    });
    this.setState({
      inputConfig: configData.getSearchInputConfig(cityList)
    })
  };
  // 基础过滤器
  handleBaseFilter(data) {
    let postRes = false;
    if (data && data.code === '000000') {
      message.success('操作成功');
      postRes = true;
    } else {
      message.error('操作失败');
    }
    return postRes;
  };
  /**
   * @description table操作触发改变事件
   * @author songs
   * @date 2019-07-12
   * @param {*} pagination
   * @param {*} filtersArg
   * @param {*} sorter
   * @memberof managementUser
   */
  handleStandardTableChange = (pagination, filtersArg, sorter, actionType) => {
    const { pageSize, current } = pagination;
    const pageNum = current;
    const pageRequest = { pageSize, pageNum };
    this.getQueryList(filtersArg, pageRequest);
  };
  async saveCityPayDate(validateRes, filter) {
    let postRes;
    try {
      postRes = filter(await saveCityPayment(validateRes));
    } catch (e) {
      postRes = e;
    }
    return postRes;
  };
  async pushSingle(data, filter) {
    let postRes;
    try {
      postRes = filter(await pushedNoticeSingle(data));
    } catch (e) {
      postRes = e;
    }
    return postRes;
  }
  async pushMultiple(data, filter) {
    let postRes;
    try {
      postRes = filter(await pushedNoticeList(data));
    } catch (e) {
      postRes = e;
    }
    return postRes;
  }
  async handleSendPush(data) {
    const config = {
      '0': this.pushMultiple,
      '1': this.pushSingle
    }
    const handleFn = config[data.pushType];
    delete data.pushType;
    return await handleFn(data, this.handleBaseFilter);
  };
  async getFormData(form, callback) {
    const { getFieldsValue, validateFields } = form;
    let res = await to(validateFields());
    return callback.call(this, res);
  }
  /**
   * @description 抽屉表单提交事件
   */
  async handleSaveCityPaymet() {
    let validateRes = await this.getFormData(this.$drawerForm.current.props.form, function (res) {
      let [validateError, validateRes] = res;
      if (validateRes.time) {
        validateRes.payYearMonth = validateRes.time.format('YYYYMM');
        delete validateRes.time;
      }
      return validateError ? false : validateRes;
    })
    if (validateRes === false) return false;
    const postRes = await this.saveCityPayDate(validateRes, this.handleBaseFilter);
    if (postRes === true) {
      handleCommand.add(this.handleChangePaymentDrawerStatus.bind(this))
      handleCommand.add(this.refreshList.bind(this))
      handleCommand.execute()
    }
    return true;
  };
  async handlePush() {
    const { activeRecord } = this.state;
    let validateRes = await this.getFormData(this.$pushDrawerForm.current.props.form, function (res) {
      let [validateError, validateRes] = res;
      return validateError ? false : validateRes;
    })
    if (validateRes === false) return;
    if (activeRecord.pushNoticeStatus === '1' && validateRes.pushType === '0') {
      return message.error('该城市多人推送已经推送过了');
    }
    validateRes.noticePassword = CryptoJS.MD5(validateRes.noticePassword).toString();
    validateRes.cityServiceType = validateRes.serviceType = Number(validateRes.serviceType)
    const postRes = await this.handleSendPush(validateRes);
    if (postRes === true) {
      handleCommand.add(this.handleChangePushDrawerStatus.bind(this))
      handleCommand.execute()
    }
    return true;
  };
  /**
   * @description 切换抽屉状态
   * @author songs
   * @param {*} visible
   * @param {*} type
   * @param {*} title
   */
  changeDrawerStatus = (visible, type = '', activeRecord = {}, event) => {
    this.setState(oldState => ({
      ...oldState,
      drawerStatus: { ...this.state.drawerStatus, [`${type}`]: { visible: visible } },
      activeRecord,
    }));
  };
  handleChangePaymentDrawerStatus(visible = false, record = {}) {
    this.changeDrawerStatus(visible, 'pay', record)
  };
  handleChangePushDrawerStatus(visible = false, record = {}) {
    this.changeDrawerStatus(visible, 'push', record)
  };
  /**
   * @description 解析抽屉内表单配置信息
   * @param {*} type
   * @returns
   */
  ravDrawerConfig = type => {
    const { activeRecord } = this.state;
    return configData.getEditConfig(activeRecord, this.props.cityList);
  };
  tableCol = () => {
    const OptionNode = ({ record }) => (
      <div className={styles.tableButtonGroup}>
        <Button
          type="link"
          style={{ marginRight: '20px' }}
          onClick={() => {
            this.handleChangePaymentDrawerStatus(true, record);
          }}
        >
          编辑
        </Button>
        <Button
          type="link"
          style={{ marginRight: '20px' }}
          onClick={() => {
            this.handleChangePushDrawerStatus(true, record);
          }}
        >
          推送
        </Button>
      </div>
    );
    return configData.getTableConfig(OptionNode)
  };

  render() {
    const { tableCol } = this;
    const { drawerStatus, inputConfig, activeRecord } = this.state;
    const { tableLoading, watermarkConfig, tableData } = this.props;
    const { list = [], pagination = {} } = tableData;
    const content = (
      <div>
        <Button style={{ float: 'right', marginLeft: '20px' }} onClick={() => this.changeDrawerStatus(true, 'pay')} type="primary">
          新增
        </Button>
      </div>
    );
    const formProp = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
    const DrawerContent = () => (
      <div className={styles.drawerContent}>
        <BaseForm wrappedComponentRef={this.$drawerForm} formProp={formProp} inputConfig={this.ravDrawerConfig()}></BaseForm>
      </div>
    );
    return (
      <div>
        <PageHeaderWrapper title="" className="hasContent">
          <div style={{ background: '#fff', padding: '20px 0px 0px 24px', marginBottom: '10px' }}>
            <SearchForm
              defaultInput={inputConfig.slice(0, 3)}
              moreInput={inputConfig.slice(3)}
              gutter={{ md: 10 }}
              useCol={{ sm: 24, md: 12, xl: 8, xxl: 8 }}
              onSearch={this.actionSearch}
            ></SearchForm>
          </div>
          <Card bordered={false}>
            <div style={{ marginBottom: '10px', height: '32px', lineHeight: '32px' }}>{content}</div>
            <StandardTable
              isWatermark
              watermark={{ ...watermarkConfig }}
              dataSource={list}
              pagination={{ ...pagination, ...pageInfo }}
              columns={tableCol()}
              loading={tableLoading}
              rowKey={(record, index) => index}
              onChange={($pagination, filtersArg, sorter) => {
                this.handleStandardTableChange($pagination, this.state.params, sorter, 'citypay/getCityPaymentList');
              }}
            ></StandardTable>
          </Card>
        </PageHeaderWrapper>
        <Modal
          title='城市最新缴费月份信息'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={e => {
            this.handleChangePaymentDrawerStatus(false);
          }}
          onOk={e => {
            this.handleSaveCityPaymet();
          }}
          visible={drawerStatus.pay.visible}
        >
          <DrawerContent></DrawerContent>
        </Modal>
        <Modal
          title='推送通知'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={e => {
            this.handleChangePushDrawerStatus(false);
          }}
          onOk={e => {
            this.handlePush();
          }}
          visible={drawerStatus.push.visible}
        >
          <Push wrappedComponentRef={this.$pushDrawerForm} activeRecord={activeRecord} />
        </Modal>
      </div>
    );
  }
}

export default CityPay;
